package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.SundayCountTotalDto;
import org.itboys.mobile.service.mongo.front.SundayFrontCountService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年2月9日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_结算（确认订单）_controller。
 *
 */
@Controller
@RequestMapping("/sunday/mobile/count")
public class SundayMobileCountController extends BaseController {
    @Autowired
    private SundayFrontCountService countService;

    /**
     * 【手机端】购物车结算（确认订单）。针对：1普通，2新品，3特卖。如果使用了爱购币，余额。请重新调用接口加载数据
     * @param request
     * @param response
     * @param cartIds
     * @param isUseAiGou
     * @param isUseBalance

     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/countCart",method= {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】购物车结算（确认订单）。针对：1普通，2新品，3特卖。如果使用了爱购币，余额。请重新调用接口加载数据")
    public void countCart(HttpServletRequest request,
             HttpServletResponse response,

        @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)。如：cardIds=1,2,3  【参与签名】") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
        @ApiParam(required = false, name = "isUseAiGou", value = "是否使用爱购币【shop==0，自营才能使用】。0否默认，1是") @RequestParam(value="isUseAiGou",required=false) Integer isUseAiGou,
        @ApiParam(required = false, name = "isUseBalance", value = "是否使用余额【shop==0，自营才能使用】。0否默认，1是") @RequestParam(value="isUseBalance",required=false) Integer isUseBalance,
         @ApiParam(required = false, name = "isUseConch", value = "是否使用贝壳【shop==0，自营才能使用】。0否默认，1是。type==6或type==10隐藏") @RequestParam(value="isUseConch",required=false) Integer isUseConch,
        @ApiParam(required = false, name = "teamIsJoin", value = "[拼团专用]是否参与拼团。0单独购买，1参与别人的，2自己开团") @RequestParam(value="teamIsJoin",required=false) Integer teamIsJoin,
        @ApiParam(required = false, name = "teamGroupId", value = "[拼团专用]要拼团的组ID。和[是否参与拼团==1]搭配使用。") @RequestParam(value="teamGroupId",required=false) Long teamGroupId,
        @ApiParam(required = false, name = "sendType", value = "配送方式。至针对自营。1，门店配送（默认），2自提") @RequestParam(value="sendType",required=false) Integer sendType,
        @ApiParam(value = "随机数【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try{
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            StringBuilder cartIdsStr=new StringBuilder();
            for(Long cartId:cartIds){
                cartIdsStr.append(cartId+",");
            }
            param.put("cartIds",cartIdsStr.substring(0,cartIdsStr.length()-1).toString());//实际是字符串。cartIds=1,2,3
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayCountTotalDto result = countService.countCart(memberId,cartIds,isUseAiGou,isUseBalance,isUseConch,teamIsJoin,teamGroupId,sendType);
            ResponseMessage.success(result);
            //JsonPageUtils.renderJson(response,houses);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/count/countCart----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 【手机端】【手机端】立即购买结算（确认订单）针对所有类型商品。以下商品类型（4海淘，5金领，6爱购币，7积分，8秒杀，9拼团，10试用）只能使用立即结算。如果使用了爱购币，余额。请重新调用接口加载数据
     * @param request
     * @param response
     * @param productId
     * @param number
     * @param isUsedAiGou
     * @param isUsedBalance
     * @param teamIsJoin
     * @param teamGroupId
     * @param nonce
     * @param sign
     */
/*    @RequestMapping(value="/countBuyNow",method= {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】立即购买结算（确认订单）针对所有类型商品。以下商品类型（4海淘，5金领，6爱购币，7积分，8秒杀，9拼团，10试用）只能使用立即结算。如果使用了爱购币，余额。请重新调用接口加载数据")
    public void countBuyNow(HttpServletRequest request,
                        HttpServletResponse response,
                            @ApiParam(required = true, name = "productId", value = "商品ID。【参与签名】") @RequestParam(value = "productId", required = true)Long  productId,
                            @ApiParam(required = true, name = "number", value = "购买数量。【参与签名】") @RequestParam(value = "number", required = true) Integer number,
                            @ApiParam(required = false, name = "isUsedAiGou", value = "是否使用爱购币【shop==0，自营才能使用】。0否默认，1是") @RequestParam(value="isUsedAiGou",required=false) Integer isUsedAiGou,
                            @ApiParam(required = false, name = "isUsedBalance", value = "是否使用余额【shop==0，自营才能使用】。0否默认，1是") @RequestParam(value="isUsedBalance",required=false) Integer isUsedBalance,

                            @ApiParam(required = false, name = "teamIsJoin", value = "[拼团专用]是否参与拼团。0否默认，1是") @RequestParam(value="teamIsJoin",required=false) Integer teamIsJoin,
                            @ApiParam(required = false, name = "teamGroupId", value = "[拼团专用]要拼团的组ID。和[是否拼团]搭配使用。") @RequestParam(value="teamGroupId",required=false) Long teamGroupId,
                            @ApiParam(value = "随机数【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try{
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }

            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayCountTotalDto result = countService.countBuyNow(
                    memberId, productId, number,
                     isUsedAiGou,
                     isUsedBalance,
                     teamIsJoin,
                     teamGroupId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/count/countBuyNow----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }*/


}
